package com.blainpeng.socketcommunicationdemo;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity implements ClientConnector.ConnectLinstener {

    private EditText mAuthDevice;
    private EditText mReceiveDevice;
    private EditText mSendingMsg;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private ClientConnector mConnector;
    //genymotion连本地网络是10.0.3.2，IDE自带的模拟器是10.0.0.2
//    private String mDstName = "172.16.42.2";    //172.16.42.3
    private String mDstName = "192.168.0.105";
    private int mDstPort = 12345;
    private ListView mListView;
    private ArrayAdapter mAdapter;
    private List<String> mData;

    private static Map<String, Socket> mClients = new LinkedHashMap<>();

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;

        mDstName = getIPAddress(this);  //荣耀10：10.75.141.56===192.168.0.102
//
//
//        mDstName = "10.158.47.177";
//        mDstName = "192.168.0.104";
//        mDstName = "180.116.93.157";
        mDstName = "106.14.18.203";
//        mDstName = "172.30.141.1";

        Log.e("onCreate===", mDstName+"===");

        initView();


//        m_myHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                cs();
//            }
//        });

        initData();

        new Thread(new Runnable(){
            @Override
            public void run() {

//                UDPSocketBroadCast.getInstance().startUDP(mDstName, mDstPort);
//                cs();



//                new UDPSocketClient().startUDP(new UDPSocketClient.UDPDataCallBack() {
//                    @Override
//                    public void mCallback(final String str) {
//
//                        m_myHandler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                mDstName = str.split("-")[1];
//
//                                Log.e("mCallback===", mDstName+"===" + str);
//
//                                initData();
//                            }
//                        });
//
//                    }
//                });


            }
        }).start();

    }

    void cs(){
        int port = 12345;
        try {
            //创建服务器
            ServerSocket serverSocket = new ServerSocket(port);
            while (true) {
                Log.e("cs===0", port+"===");

                //获取客户端的连接
                final Socket socket = serverSocket.accept();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {


                            //读取从客户端发送过来的数据
                            InputStream inputStream = socket.getInputStream();

                            Log.e("cs===1", socket+"===");

                            byte[] buffer = new byte[1024];
                            int len = -1;
                            while ((len = inputStream.read(buffer)) != -1) {
                                final String data = new String(buffer, 0, len);

                                m_myHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
                                    }
                                });


//                                //先认证客户端
//                                if (data.startsWith("#")) {
//                                    mClients.put(data, socket);
//                                } else {
//                                    //将数据发送给指定的客户端
//                                    String[] split = data.split("#");
//                                    Socket c = mClients.get("#" + split[0]);
//                                    OutputStream outputStream = c.getOutputStream();
//                                    outputStream.write(split[1].getBytes());
//
//                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    break;

                default:
                    break;
            }
            return false;
        }
    });

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }


    private void initView() {
        mAuthDevice = (EditText) findViewById(R.id.et_auth_device);
        mReceiveDevice = (EditText) findViewById(R.id.et_receive_device);
        mSendingMsg = (EditText) findViewById(R.id.et_send_message);
        mListView = (ListView) findViewById(R.id.listview);
    }

    private void initData() {
        mHandlerThread = new HandlerThread("MainActivity", android.os.Process.THREAD_PRIORITY_BACKGROUND);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
        mConnector = new ClientConnector(mDstName, mDstPort);
        mConnector.setOnConnectLinstener(this);
        mData = new ArrayList<>();
        mAdapter = new ArrayAdapter(this, R.layout.item, R.id.tv_text, mData);
        mListView.setAdapter(mAdapter);

    }


    public void connectServer(View view) {

        mHandler.post(new ConnectRunnable());
    }

    @Override
    public void onReceiveData(final String data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mData.add(data);
                mAdapter.notifyDataSetChanged();
//                Toast.makeText(MainActivity.this, "data=" + data, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private class ConnectRunnable implements Runnable {


        @Override
        public void run() {
            try {

                Log.e("ConnectRunnable===", mConnector+"===");

                mConnector.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void authClient(View view) {

        String auth = mAuthDevice.getText().toString().trim();
        if (TextUtils.isEmpty(auth)) {
            Toast.makeText(this, "认证信息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            mConnector.auth(auth);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(View view) {
        String receiver = mReceiveDevice.getText().toString().trim();
        String msg = mSendingMsg.getText().toString().trim();
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(receiver)) {
            Toast.makeText(this, "信息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.e("sendMessage===", mConnector+"==="+receiver+"==="+msg);

        try {
//            mData.add(msg);
            mConnector.send(receiver, msg);
//            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void disconnectServer(View view) {
        try {
            mConnector.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
